/**
 * 数据源管理模块
 * 处理数据源相关的所有业务逻辑
 */
class DataSourceManager {
    constructor() {
        this.datasources = [];
        this.currentPreviewDatasourceId = null;
        this.previewTable = null;
        this.init();
    }
    
    /**
     * 初始化
     */
    init() {
        this.bindEvents();
        this.initializeHelpFeatures();
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        // 数据源类型选择
        document.addEventListener('click', (e) => {
            if (e.target.closest('.datasource-type')) {
                this.selectDatasourceType(e.target.closest('.datasource-type').dataset.type);
            }
        });
        
        // 数据库类型变化
        const dbTypeSelect = document.getElementById('dbType');
        if (dbTypeSelect) {
            dbTypeSelect.addEventListener('change', () => this.updateDefaultPort());
        }
        
        // 帮助按钮事件
        document.addEventListener('click', (e) => {
            if (e.target.closest('.help-button')) {
                this.showHelpDialog();
            }
        });
        
        // 监听模态框显示事件，初始化文件上传
        document.addEventListener('click', (e) => {
            if (e.target.closest('button') && e.target.closest('button').onclick && 
                e.target.closest('button').onclick.toString().includes('showAddDatasourceModal')) {
                // 防止重复初始化
                if (!window.fileUploadInitialized) {
                    window.fileUploadInitialized = true;
                    setTimeout(() => {
                        if (typeof initializeFileUpload === 'function') {
                            initializeFileUpload();
                        }
                    }, 100);
                }
            }
        });
    }
    
    /**
     * 加载数据源列表
     */
    async loadDatasources() {
        try {
            // 检查必要的依赖
            if (typeof ApiService === 'undefined') {
                console.error('ApiService未加载，请检查JavaScript加载顺序');
                this.showErrorState('系统组件未加载完成，请刷新页面');
                return;
            }

            this.showPageLoadingState();

            const response = await ApiService.getDataSources();
            
            if (response.success) {
                this.datasources = response.data;
                this.renderDatasourceList();
                
                // 加载统计信息
                await this.loadStatistics();
                
                // 如果没有数据源，显示友好提示
                if (this.datasources.length === 0) {
                    NotificationService.info('暂无数据源，点击"新增数据源"开始添加', 3000);
                }
            } else {
                const errorMessage = response.message || '数据源加载失败';
                ErrorHandler.handleApiError(new Error(errorMessage), 'load_datasources');
                this.showEmptyState();
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'load_datasources');
            this.showEmptyState();
        } finally {
            this.hidePageLoadingState();
        }
    }
    
    /**
     * 加载数据源统计信息
     */
    async loadStatistics() {
        try {
            const response = await fetch('/api/data-sources/statistics');
            const result = await response.json();
            
            if (result.code === 200) {
                const stats = result.data;
                this.updateStatisticsDisplay(stats);
            } else {
                console.error('获取统计信息失败:', result.message);
            }
        } catch (error) {
            console.error('加载统计信息失败:', error);
        }
    }
    
    /**
     * 更新统计信息显示
     */
    updateStatisticsDisplay(stats) {
        const elements = {
            totalDatasources: document.getElementById('totalDatasources'),
            activeDatasources: document.getElementById('activeDatasources'),
            errorDatasources: document.getElementById('errorDatasources'),
            excelDatasources: document.getElementById('excelDatasources')
        };
        
        if (elements.totalDatasources) {
            elements.totalDatasources.textContent = stats.total_count || 0;
        }
        
        if (elements.activeDatasources) {
            elements.activeDatasources.textContent = stats.active_count || 0;
        }
        
        if (elements.errorDatasources) {
            elements.errorDatasources.textContent = stats.error_count || 0;
        }
        
        if (elements.excelDatasources) {
            elements.excelDatasources.textContent = stats.excel_count || 0;
        }
    }
    
    /**
     * 渲染数据源列表
     */
    renderDatasourceList() {
        const container = document.getElementById('datasourceList');
        if (!container) return;
        
        if (this.datasources.length === 0) {
            this.showEmptyState();
            return;
        }
        
        const html = this.datasources.map(datasource => this.createDatasourceCard(datasource)).join('');
        container.innerHTML = html;
        
        // 绑定卡片事件
        this.bindDatasourceCardEvents();
    }
    
    /**
     * 创建数据源卡片HTML
     */
    createDatasourceCard(datasource) {
        const typeIcon = datasource.type === 'database' ? 'fas fa-database' : 'fas fa-file-excel';
        const statusColor = datasource.status === 'active' ? 'text-green-600' : 'text-gray-500';
        const statusText = datasource.status === 'active' ? '已连接' : '未连接';
        
        return `
            <div class="datasource-card bg-white p-6 rounded-lg border border-slate-200 hover:border-indigo-300" data-id="${datasource.id}">
                <div class="flex items-start justify-between mb-4">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-indigo-100 rounded-lg flex items-center justify-center mr-4">
                            <i class="${typeIcon} text-indigo-600"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold text-slate-800">${datasource.name}</h3>
                            <p class="text-sm text-slate-500">${datasource.description || '无描述'}</p>
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <span class="status-indicator w-2 h-2 ${statusColor} rounded-full"></span>
                        <span class="text-sm ${statusColor}">${statusText}</span>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <span class="text-sm text-slate-500">类型</span>
                        <p class="font-medium">${datasource.type === 'database' ? '数据库' : 'Excel文件'}</p>
                    </div>
                    <div>
                        <span class="text-sm text-slate-500">创建时间</span>
                        <p class="font-medium">${this.formatDate(datasource.created_at)}</p>
                    </div>
                </div>
                
                <div class="flex justify-between items-center">
                    <div class="flex space-x-2">
                        <button onclick="dataSourceManager.showDatasourceDetail(${datasource.id})" 
                                class="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition">
                            <i class="fas fa-eye mr-1"></i>查看
                        </button>
                        <button onclick="dataSourceManager.previewDatasource(${datasource.id})" 
                                class="px-3 py-1 text-sm bg-green-100 text-green-700 rounded hover:bg-green-200 transition">
                            <i class="fas fa-table mr-1"></i>预览
                        </button>
                    </div>
                    <div class="flex space-x-2">
                        <button onclick="dataSourceManager.editDatasource(${datasource.id})" 
                                class="text-slate-400 hover:text-slate-600 transition">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="dataSourceManager.deleteDatasource(${datasource.id})" 
                                class="text-slate-400 hover:text-red-600 transition">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 选择数据源类型
     */
    selectDatasourceType(type) {
        // 更新选中状态
        document.querySelectorAll('.datasource-type').forEach(el => {
            el.classList.remove('selected');
        });
        document.querySelector(`[data-type="${type}"]`).classList.add('selected');
        
        // 显示对应的配置区域
        document.getElementById('databaseConfig').classList.toggle('hidden', type !== 'database');
        document.getElementById('excelConfig').classList.toggle('hidden', type !== 'excel');
    }
    
    /**
     * 更新默认端口
     */
    updateDefaultPort() {
        const dbType = document.getElementById('dbType').value;
        const portInput = document.getElementById('dbPort');
        
        const defaultPorts = {
            'mysql': '3306',
            'postgresql': '5432',
            'sqlite': '',
            'oracle': '1521',
            'sqlserver': '1433'
        };
        
        if (portInput && !portInput.value) {
            portInput.value = defaultPorts[dbType] || '';
        }
    }
    
    /**
     * 测试连接
     */
    async testConnection(button) {
        const originalText = button.innerHTML;
        
        try {
            this.showButtonLoadingState(button, '正在测试连接...');
            
            const config = this.getDatasourceConfig();
            
            const response = await ApiService.testConnection(config);
            
            if (response.success) {
                NotificationService.success('连接测试成功！', 2000);
            } else {
                ErrorHandler.handleApiError(new Error(response.message || '连接测试失败'), 'test_connection');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'test_connection');
        } finally {
            this.hideButtonLoadingState(button, originalText);
        }
    }
    
    /**
     * 预览编辑中的数据源
     */
    async previewEditDatasource() {
        try {
            const config = this.getDatasourceConfig();
            
            console.log('预览数据源配置:', config);
            
            // 对于编辑模式，我们需要使用当前编辑的数据源ID
            let datasourceId = this.currentEditDatasourceId;
            
            if (!datasourceId) {
                // 如果是新创建的数据源，先临时保存
                NotificationService.warning('请先保存数据源后再预览', 2000);
                return;
            }
            
            // 获取表名
            let tableName = null;
            if (config.type === 'database') {
                tableName = config.config.table_name || config.config.table;
                console.log('数据库表名:', tableName);
                
                if (!tableName) {
                    NotificationService.warning('请先设置表名后再预览数据', 3000);
                    // 聚焦到表名输入框
                    const tableInput = document.getElementById('dbTable');
                    if (tableInput) {
                        tableInput.focus();
                        tableInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                    return;
                }
            }
            
            // 显示预览模态框
            aiAnalysisPage.showDataPreviewModal();
            
            // 设置预览数据源ID和表名
            this.currentPreviewDatasourceId = datasourceId;
            this.currentPreviewTableName = tableName;
            
            // 显示加载提示
            NotificationService.info(`正在加载表 "${tableName}" 的数据...`, 2000);
            
            // 加载预览数据，传递表名
            await this.loadPreviewData(1, 20, tableName);
            
        } catch (error) {
            console.error('预览编辑数据源失败:', error);
            
            // 提供更具体的错误信息
            let errorMessage = '预览数据失败';
            if (error.message.includes('table_name')) {
                errorMessage = '表名配置错误，请检查表名设置';
            } else if (error.message.includes('连接') || error.message.includes('connection')) {
                errorMessage = '数据库连接失败，请检查连接配置';
            } else if (error.message.includes('不存在') || error.message.includes('not exist')) {
                errorMessage = '表不存在，请检查表名是否正确';
            }
            
            ErrorHandler.handleApiError(new Error(errorMessage), 'preview_data');
        }
    }
    
    /**
     * 获取数据源配置
     */
    getDatasourceConfig() {
        const type = document.querySelector('.datasource-type.selected').dataset.type;
        
        if (type === 'database') {
            const config = {
                type: 'database',
                config: {
                    database_type: document.getElementById('dbType').value,
                    host: document.getElementById('dbHost').value,
                    port: document.getElementById('dbPort').value,
                    database: document.getElementById('dbDatabase').value,
                    username: document.getElementById('dbUsername').value,
                    password: document.getElementById('dbPassword').value,
                    schema: document.getElementById('dbSchema').value || 'public',
                    charset: document.getElementById('dbCharset').value,
                    timeout: parseInt(document.getElementById('dbTimeout').value) || 30,
                    table_name: document.getElementById('dbTable').value
                }
            };
            
            // 添加高级配置（如果存在且不为空）
            const sslMode = document.getElementById('dbSslMode').value;
            if (sslMode) {
                config.config.ssl_mode = sslMode;
            }
            
            const maxRetry = document.getElementById('dbMaxRetry').value;
            if (maxRetry) {
                config.config.max_retry = parseInt(maxRetry);
            }
            
            return config;
        } else {
            return {
                type: 'excel',
                config: {
                    file_path: document.getElementById('excelFile').value,
                    sheet_name: document.getElementById('sheetName').value,
                    has_header: document.getElementById('hasHeader').checked
                }
            };
        }
    }
    
    /**
     * 保存数据源
     */
    async saveDatasource() {
        try {
            // 检查是否为Excel类型
            const selectedType = document.querySelector('.datasource-type.selected');
            const isExcelType = selectedType && selectedType.dataset.type === 'excel';
            
            let response;
            
            if (isExcelType) {
                // Excel文件上传处理
                response = await this.uploadExcelDatasource();
            } else {
                // 普通数据源处理
                const formData = this.getDatasourceFormData();
                if (!formData) {
                    return;
                }
                
                // 检查是否为编辑模式
                const modal = document.getElementById('addDatasourceModal');
                const isEditMode = modal && modal.dataset.editMode === 'true';
                const editId = modal ? parseInt(modal.dataset.editId) : null;
                
                NotificationService.info(isEditMode ? '正在更新数据源...' : '正在保存数据源...');
                
                if (isEditMode && editId) {
                    // 更新现有数据源
                    response = await ApiService.updateDataSource(editId, formData);
                } else {
                    // 创建新数据源
                    response = await ApiService.createDataSource(formData);
                }
            }

            if (response.success) {
                const successMessage = isExcelType ? 'Excel文件上传成功！' : 
                    (response.data && response.data.id ? '数据源更新成功！' : '数据源保存成功！');
                NotificationService.success(successMessage, 3000);
                
                // 延迟关闭模态框，让用户看到成功消息
                setTimeout(() => {
                    this.closeAddDatasourceModal();
                    this.loadDatasources();
                }, 1000);
            } else {
                const errorMessage = response.message || (isExcelType ? '上传失败' : '保存失败');
                ErrorHandler.handleApiError(new Error(errorMessage), 'save_datasource');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'save_datasource');
        }
    }
    
    /**
     * 获取表单数据
     */
    getDatasourceFormData() {
        const selectedType = document.querySelector('.datasource-type.selected');
        if (!selectedType) {
            NotificationService.error('请选择数据源类型');
            return null;
        }

        const type = selectedType.dataset.type;
        const nameInput = document.querySelector('#addDatasourceModal input[placeholder="请输入数据源名称"]');
        const name = nameInput ? nameInput.value.trim() : '';
        
        if (!name) {
            NotificationService.error('请输入数据源名称');
            return null;
        }

        const formData = {
            name: name,
            type: type,
            description: document.querySelector('#addDatasourceModal input[placeholder="请输入数据源描述"]')?.value.trim() || ''
        };

        if (type === 'database') {
            const dbType = document.getElementById('dbType').value;
            const host = document.getElementById('dbHost').value.trim();
            const port = document.getElementById('dbPort').value;
            const database = document.getElementById('dbDatabase').value.trim();
            const username = document.getElementById('dbUsername').value.trim();
            const password = document.getElementById('dbPassword').value;

            // 必填字段验证
            if (!dbType || !host || !database || !username || !password) {
                NotificationService.error('请填写所有必填的数据库连接信息');
                return null;
            }

            // SQLite特殊处理
            if (dbType === 'sqlite') {
                if (!database) {
                    NotificationService.error('SQLite数据库文件路径不能为空');
                    return null;
                }
            }

            formData.config = {
                database_type: dbType,
                host: host,
                port: parseInt(port) || this.getDefaultPort(dbType),
                database: database,
                username: username,
                password: password,
                charset: document.getElementById('dbCharset').value || 'utf8mb4',
                timeout: parseInt(document.getElementById('dbTimeout').value) || 30,
                table_name: document.getElementById('dbTable').value.trim(),
                schema: document.getElementById('dbSchema').value.trim(),
                ssl_mode: document.getElementById('dbSslMode').value,
                max_retry: parseInt(document.getElementById('dbMaxRetry').value) || 3
            };
        } else if (type === 'excel') {
            const excelFile = document.getElementById('excelFile');
            if (!excelFile || !excelFile.files || excelFile.files.length === 0) {
                NotificationService.error('请选择Excel文件');
                return null;
            }
            
            // Excel文件数据将直接通过表单提交处理
            // 这里只需要返回基本信息，实际的文件上传由单独的API处理
            return {
                name: name,
                type: type,
                description: document.querySelector('#addDatasourceModal input[placeholder="请输入数据源描述"]')?.value.trim() || ''
            };
        }

        return formData;
    }
    
    /**
     * 获取数据库默认端口
     */
    getDefaultPort(dbType) {
        const defaultPorts = {
            'mysql': 3306,
            'postgresql': 5432,
            'oracle': 1521,
            'sqlserver': 1433,
            'sqlite': 0
        };
        return defaultPorts[dbType] || 3306;
    }
    
    /**
     * 关闭新增数据源模态框
     */
    closeAddDatasourceModal() {
        const modal = document.getElementById('addDatasourceModal');
        if (modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            this.resetDatasourceForm();
            
            // 重置编辑模式
            delete modal.dataset.editMode;
            delete modal.dataset.editId;
            
            // 重置标题
            const titleElement = modal.querySelector('h2');
            if (titleElement) {
                titleElement.textContent = '新增数据源';
            }
        }
    }
    
    /**
     * 重置数据源表单
     */
    resetDatasourceForm() {
        document.querySelectorAll('.datasource-type').forEach(el => {
            el.classList.remove('selected');
        });
        
        const databaseConfig = document.getElementById('databaseConfig');
        const excelConfig = document.getElementById('excelConfig');
        if (databaseConfig) databaseConfig.classList.add('hidden');
        if (excelConfig) excelConfig.classList.add('hidden');
        
        // 清空表单字段
        document.querySelectorAll('#addDatasourceModal input, #addDatasourceModal select').forEach(input => {
            if (input.type === 'radio' || input.type === 'checkbox') {
                input.checked = false;
            } else {
                input.value = '';
            }
        });
    }
    
    /**
     * 预览数据源数据
     */
    async previewDatasource(datasourceId) {
        this.currentPreviewDatasourceId = datasourceId;
        
        // 显示预览模态框
        const modal = document.getElementById('dataPreviewModal');
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }
        
        // 初始化预览表格
        await this.initPreviewTable();
        await this.loadPreviewData();
    }
    
    /**
     * 初始化预览表格
     */
    initPreviewTable() {
        const container = document.getElementById('previewDataContainer');
        if (!container) return;
        
        // 创建预览表格实例
        this.previewTable = new PreviewTable('previewDataContainer', {
            pageSize: 20,
            showPagination: true,
            showStats: true,
            sortable: true
        });
        
        // 暴露给全局作用域，供HTML模板使用
        window.previewTable = this.previewTable;
        
        // 监听分页变化事件
        container.addEventListener('pageChange', (e) => {
            // 分页时也传递当前表名
            this.loadPreviewData(e.detail.page, e.detail.pageSize, this.currentPreviewTableName);
        });
    }
    
    /**
     * 加载预览数据
     */
    async loadPreviewData(page = 1, pageSize = 20, tableName = null) {
        if (!this.previewTable) return;
        
        try {
            // 构建请求参数
            const requestParams = {
                limit: pageSize,
                offset: (page - 1) * pageSize
            };
            
            // 如果指定了表名，添加到请求参数
            if (tableName) {
                requestParams.table_name = tableName;
                console.log('预览表名:', tableName);
            }
            
            console.log('预览请求参数:', requestParams);
            
            const response = await ApiService.previewData(
                this.currentPreviewDatasourceId,
                requestParams
            );
            
            console.log('预览响应:', response);
            
            // 处理API响应格式
            let data;
            if (response.success) {
                // 标准API响应格式 {success: true, data: {...}}
                data = response.data;
            } else if (response.code === 200) {
                // 新API响应格式 {code: 200, data: {...}}
                data = response.data;
            } else if (response.data && !response.success) {
                // 直接返回数据格式 {data: {...}, columns: [...]}
                data = response;
            } else {
                throw new Error(response.message || '数据加载失败');
            }
            
            // 验证必要的数据字段
            if (!data || typeof data !== 'object') {
                throw new Error('返回数据格式不正确');
            }
            
            // 安全地获取数据
            const tableData = data.data || [];
            const columns = data.columns || (tableData.length > 0 ? Object.keys(tableData[0]) : []);
            const totalRecords = data.total_records || tableData.length;
            const executionTime = data.execution_time || 0;
            
            console.log('解析后的数据:', {
                tableData: tableData.length,
                columns: columns.length,
                totalRecords,
                executionTime
            });
            
            // 提取列名数组（从对象数组中提取name字段）
            const columnNames = columns.map(col => col.name || col);
            
            // 加载到预览表格
            this.previewTable.loadData(tableData, columnNames, totalRecords, executionTime);
            
            // 显示成功消息，包含表名信息
            const tableNameDisplay = data.table_name || tableName || '数据表';
            NotificationService.success(`预览数据加载成功 (${tableNameDisplay})`, 2000);
            
        } catch (error) {
            console.error('预览数据加载失败:', error);
            
            // 提供更详细的错误信息
            let errorMessage = error.message || '数据加载失败';
            if (tableName) {
                errorMessage = `表 "${tableName}" 预览失败: ${errorMessage}`;
            }
            
            ErrorHandler.handleApiError(new Error(errorMessage), 'preview_data');
        }
    }
    
    /**
     * 显示页面级加载状态
     */
    showPageLoadingState() {
        const loadingState = document.getElementById('loadingState');
        const datasourceList = document.getElementById('datasourceList');
        const emptyState = document.getElementById('emptyState');
        
        if (loadingState) loadingState.classList.remove('hidden');
        if (datasourceList) datasourceList.classList.add('hidden');
        if (emptyState) emptyState.classList.add('hidden');
    }
    
    /**
     * 隐藏页面级加载状态
     */
    hidePageLoadingState() {
        const loadingState = document.getElementById('loadingState');
        const datasourceList = document.getElementById('datasourceList');

        if (loadingState) loadingState.classList.add('hidden');
        if (datasourceList) datasourceList.classList.remove('hidden');
    }

    /**
     * 显示错误状态
     */
    showErrorState(message) {
        const loadingState = document.getElementById('loadingState');
        const datasourceList = document.getElementById('datasourceList');
        const emptyState = document.getElementById('emptyState');

        if (loadingState) loadingState.classList.add('hidden');
        if (datasourceList) datasourceList.classList.add('hidden');
        if (emptyState) {
            emptyState.classList.remove('hidden');
            const emptyStateText = emptyState.querySelector('p');
            if (emptyStateText) {
                emptyStateText.textContent = message;
            }
        }
    }
    
    /**
     * 显示按钮级加载状态
     */
    showButtonLoadingState(button, loadingText) {
        if (button) {
            button.disabled = true;
            button.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>${loadingText}`;
        }
    }
    
    /**
     * 隐藏按钮级加载状态
     */
    hideButtonLoadingState(button, originalText) {
        if (button) {
            button.disabled = false;
            button.innerHTML = originalText;
        }
    }
    
    /**
     * 显示空状态
     */
    showEmptyState() {
        const emptyState = document.getElementById('emptyState');
        const datasourceList = document.getElementById('datasourceList');
        
        if (emptyState) emptyState.classList.remove('hidden');
        if (datasourceList) datasourceList.classList.add('hidden');
    }
    
    /**
     * 格式化日期
     */
    formatDate(dateString) {
        if (!dateString) return '';
        return new Date(dateString).toLocaleString('zh-CN');
    }
    
    /**
     * 绑定数据源卡片事件
     */
    bindDatasourceCardEvents() {
        // 可以在这里添加更多的事件绑定
    }
    
    /**
     * 显示数据源详情
     */
    async showDatasourceDetail(datasourceId) {
        try {
            const response = await ApiService.getDataSource(datasourceId);
            
            if (response.success) {
                const datasource = response.data;
                this.showDatasourceDetailModal(datasource);
            } else {
                ErrorHandler.handleApiError(new Error(response.message || '获取数据源详情失败'), 'get_datasource_detail');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'get_datasource_detail');
        }
    }
    
    /**
     * 显示数据源详情模态框
     */
    showDatasourceDetailModal(datasource) {
        // 创建或更新详情模态框
        let modal = document.getElementById('datasourceDetailModal');
        if (!modal) {
            modal = this.createDatasourceDetailModal();
            document.body.appendChild(modal);
        }
        
        // 填充数据
        document.getElementById('detailName').textContent = datasource.name;
        document.getElementById('detailType').textContent = datasource.type === 'database' ? '数据库' : 'Excel文件';
        document.getElementById('detailStatus').textContent = datasource.status === 'active' ? '已连接' : '未连接';
        document.getElementById('detailDescription').textContent = datasource.description || '无描述';
        document.getElementById('detailCreated').textContent = this.formatDate(datasource.created_at);
        
        // 显示配置信息
        this.renderDetailConfig(datasource);
        
        // 显示模态框
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
    
    /**
     * 创建数据源详情模态框
     */
    createDatasourceDetailModal() {
        const modal = document.createElement('div');
        modal.id = 'datasourceDetailModal';
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden';
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-2xl font-bold text-slate-800" id="detailName">数据源详情</h2>
                        <button onclick="document.getElementById('datasourceDetailModal').classList.add('hidden')" 
                                class="text-slate-400 hover:text-slate-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-1">数据源类型</label>
                                <p class="text-slate-900" id="detailType">-</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-1">状态</label>
                                <p class="text-slate-900" id="detailStatus">-</p>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">描述</label>
                            <p class="text-slate-900" id="detailDescription">-</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">创建时间</label>
                            <p class="text-slate-900" id="detailCreated">-</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">配置信息</label>
                            <div id="detailConfig" class="bg-slate-50 p-4 rounded-lg text-sm">
                                <!-- 配置信息将在这里动态填充 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        return modal;
    }
    
    /**
     * 渲染详情配置
     */
    renderDetailConfig(datasource) {
        const configContainer = document.getElementById('detailConfig');
        if (!configContainer) return;
        
        let configHtml = '';
        if (datasource.type === 'database') {
            const config = datasource.config || {};
            configHtml = `
                <div class="space-y-2">
                    <div><strong>数据库类型:</strong> ${config.database_type || '-'}</div>
                    <div><strong>主机:</strong> ${config.host || '-'}</div>
                    <div><strong>端口:</strong> ${config.port || '-'}</div>
                    <div><strong>数据库:</strong> ${config.database || '-'}</div>
                    <div><strong>用户名:</strong> ${config.username || '-'}</div>
                    <div><strong>表名:</strong> ${config.table_name || '-'}</div>
                    <div><strong>字符集:</strong> ${config.charset || '-'}</div>
                    <div><strong>超时时间:</strong> ${config.timeout || '-'}秒</div>
                </div>
            `;
        } else if (datasource.type === 'excel') {
            const config = datasource.config || {};
            configHtml = `
                <div class="space-y-2">
                    <div><strong>文件路径:</strong> ${config.file_path || '-'}</div>
                    <div><strong>文件名:</strong> ${config.file_name || '-'}</div>
                    <div><strong>工作表:</strong> ${config.sheet_name || '-'}</div>
                    <div><strong>包含标题:</strong> ${config.has_header ? '是' : '否'}</div>
                </div>
            `;
        }
        
        configContainer.innerHTML = configHtml;
    }
    
    /**
     * 编辑数据源
     */
    async editDatasource(datasourceId) {
        try {
            const response = await ApiService.getDataSource(datasourceId);
            
            if (response.success) {
                const datasource = response.data;
                this.showEditDatasourceModal(datasource);
            } else {
                ErrorHandler.handleApiError(new Error(response.message || '获取数据源信息失败'), 'get_datasource_edit');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'get_datasource_edit');
        }
    }
    
    /**
     * 显示编辑数据源模态框
     */
    showEditDatasourceModal(datasource) {
        // 使用现有的新增数据源模态框，但设置为编辑模式
        const modal = document.getElementById('addDatasourceModal');
        if (!modal) return;
        
        // 设置标题
        const titleElement = modal.querySelector('h2');
        if (titleElement) {
            titleElement.textContent = '编辑数据源';
        }
        
        // 填充表单数据
        this.populateEditForm(datasource);
        
        // 显示模态框
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        
        // 设置编辑模式
        modal.dataset.editMode = 'true';
        modal.dataset.editId = datasource.id;
    }
    
    /**
     * 填充编辑表单
     */
    populateEditForm(datasource) {
        // 选择数据源类型
        this.selectDatasourceType(datasource.type);
        
        // 填充基本信息
        const nameInput = document.querySelector('#addDatasourceModal input[placeholder="请输入数据源名称"]');
        const descInput = document.querySelector('#addDatasourceModal input[placeholder="请输入数据源描述"]');
        
        if (nameInput) nameInput.value = datasource.name;
        if (descInput) descInput.value = datasource.description || '';
        
        // 填充配置信息
        if (datasource.type === 'database') {
            const config = datasource.config || {};
            // 修复数据库类型字段映射问题 - 优先使用 db_type，如果没有则尝试 database_type
            const dbType = config.db_type || config.database_type || '';
            document.getElementById('dbType').value = dbType;
            document.getElementById('dbHost').value = config.host || '';
            document.getElementById('dbPort').value = config.port || '';
            document.getElementById('dbDatabase').value = config.database || '';
            document.getElementById('dbUsername').value = config.username || '';
            document.getElementById('dbPassword').value = config.password || '';
            document.getElementById('dbTable').value = config.table_name || '';
            document.getElementById('dbCharset').value = config.charset || '';
            document.getElementById('dbTimeout').value = config.timeout || '';
            document.getElementById('dbSchema').value = config.schema || '';
            
            // 触发端口更新
            this.updateDefaultPort();
        } else if (datasource.type === 'excel') {
            const config = datasource.config || {};
            // 对于文件输入，不能直接设置value，只显示文件名信息
            const excelFileInput = document.getElementById('excelFile');
            if (excelFileInput && config.file_name) {
                // 显示文件名信息但不设置文件输入的值（安全限制）
                this.showExcelFileInfo({
                    name: config.file_name,
                    size: config.file_size || 0,
                    sheetNames: config.sheet_names || [config.sheet_name || 'Sheet1']
                });
            }
            
            // 设置其他配置
            if (config.sheet_name) {
                document.getElementById('sheetName').value = config.sheet_name;
            }
            document.getElementById('hasHeader').checked = config.has_header !== false; // 默认为true
        }
    }
    
    /**
     * 显示Excel文件信息（编辑模式）
     */
    showExcelFileInfo(fileInfo) {
        const dropZoneContent = document.getElementById('dropZoneContent');
        const fileInfoElement = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        
        if (dropZoneContent && fileInfoElement && fileName && fileSize) {
            // 隐藏默认内容，显示文件信息
            dropZoneContent.classList.remove('hidden');
            fileInfoElement.classList.remove('hidden');
            fileName.textContent = fileInfo.name;
            fileSize.textContent = this.formatFileSize(fileInfo.size);
            
            // 填充工作表名称
            if (fileInfo.sheetNames && fileInfo.sheetNames.length > 0) {
                this.populateSheetNames(fileInfo.sheetNames);
                document.getElementById('sheetName').value = fileInfo.sheetNames[0];
            }
        }
    }
    
    /**
     * 上传Excel数据源
     */
    async uploadExcelDatasource() {
        const formData = new FormData();
        const fileInput = document.getElementById('excelFile');
        
        if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
            NotificationService.error('请选择Excel文件');
            return;
        }
        
        const file = fileInput.files[0];
        const name = document.querySelector('#addDatasourceModal input[placeholder="请输入数据源名称"]').value.trim();
        const description = document.querySelector('#addDatasourceModal input[placeholder="请输入数据源描述"]').value.trim();
        const sheetName = document.getElementById('sheetName').value.trim();
        const hasHeader = document.getElementById('hasHeader').checked;
        
        if (!name) {
            NotificationService.error('请输入数据源名称');
            return;
        }
        
        formData.append('file', file);
        formData.append('name', name);
        formData.append('description', description);
        if (sheetName) {
            formData.append('sheet_name', sheetName);
        }
        formData.append('has_header', hasHeader);
        
        NotificationService.info('正在上传Excel文件...');
        
        return await ApiService.uploadExcel(formData);
    }
    
    /**
     * 删除数据源
     */
    async deleteDatasource(datasourceId) {
        // 确认删除
        if (!confirm('确定要删除这个数据源吗？此操作不可恢复。')) {
            return;
        }
        
        try {
            const response = await ApiService.deleteDataSource(datasourceId);
            
            if (response.success) {
                NotificationService.success('数据源删除成功', 3000);
                await this.loadDatasources();
            } else {
                ErrorHandler.handleApiError(new Error(response.message || '删除数据源失败'), 'delete_datasource');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'delete_datasource');
        }
    }
    
    /**
     * 初始化帮助功能
     */
    initializeHelpFeatures() {
        // 添加帮助按钮到页面
        this.addHelpButton();
        
        // 自动开始引导（如果是首次使用）
        if (window.userGuideService) {
            window.userGuideService.autoStartGuide('datasource');
        }
    }
    
    /**
     * 添加帮助按钮
     */
    addHelpButton() {
        const header = document.querySelector('.page-header');
        if (!header) return;
        
        const helpButton = document.createElement('button');
        helpButton.className = 'help-button ml-3 px-3 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition flex items-center';
        helpButton.innerHTML = '<i class="fas fa-question-circle mr-2"></i>使用帮助';
        
        header.appendChild(helpButton);
    }
    
    /**
     * 显示帮助对话框
     */
    showHelpDialog() {
        const helpContent = `
            <div class="space-y-4">
                <div>
                    <h3 class="text-lg font-semibold mb-2">🔗 如何添加数据源</h3>
                    <ol class="list-decimal list-inside space-y-1 text-sm text-gray-600">
                        <li>点击"新增数据源"按钮</li>
                        <li>选择数据源类型（数据库或Excel文件）</li>
                        <li>填写数据源名称和描述</li>
                        <li>配置连接信息（数据库类型、主机、端口等）</li>
                        <li>点击"测试连接"验证配置</li>
                        <li>保存数据源配置</li>
                    </ol>
                </div>
                
                <div>
                    <h3 class="text-lg font-semibold mb-2">📊 数据源操作</h3>
                    <ul class="list-disc list-inside space-y-1 text-sm text-gray-600">
                        <li><strong>查看</strong>：查看数据源详细信息和配置</li>
                        <li><strong>预览</strong>：预览数据源中的表结构和数据</li>
                        <li><strong>编辑</strong>：修改数据源配置信息</li>
                        <li><strong>删除</strong>：删除不需要的数据源</li>
                        <li><strong>测试</strong>：测试数据源连接状态</li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="text-lg font-semibold mb-2">💡 常见问题</h3>
                    <div class="space-y-2 text-sm text-gray-600">
                        <div>
                            <strong>Q: 连接测试失败怎么办？</strong>
                            <p>检查主机地址、端口、用户名、密码是否正确，确保数据库服务正常运行</p>
                        </div>
                        <div>
                            <strong>Q: Excel文件上传失败？</strong>
                            <p>确保文件格式为.xlsx或.xls，文件大小不超过10MB</p>
                        </div>
                        <div>
                            <strong>Q: 数据预览为空？</strong>
                            <p>检查表名是否正确，确保用户有查询权限</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        this.showModal('使用帮助', helpContent);
    }
    
    /**
     * 显示模态框
     * @param {string} title - 标题
     * @param {string} content - 内容
     */
    showModal(title, content) {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        modal.innerHTML = `
            <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-2xl font-bold text-slate-800">${title}</h2>
                        <button onclick="this.closest('.fixed').remove()" 
                                class="text-slate-400 hover:text-slate-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    ${content}
                    <div class="mt-6 flex justify-end">
                        <button onclick="this.closest('.fixed').remove()" 
                                class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition">
                            知道了
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });
    }
    
    /**
     * 测试数据源连接
     */
    async testDatasource(datasourceId) {
        try {
            const response = await ApiService.testDataSource(datasourceId);
            
            if (response.success) {
                NotificationService.success('连接测试成功！', 2000);
            } else {
                ErrorHandler.handleApiError(new Error(response.message || '连接测试失败'), 'test_datasource');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'test_datasource');
        }
    }
    
    /**
     * 处理文件选择
     */
    handleFileSelect(file) {
        console.log('选择文件:', file);
        
        // 验证文件类型
        const validTypes = ['.xlsx', '.xls', '.csv'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        
        if (!validTypes.includes(fileExtension)) {
            NotificationService.error('不支持的文件格式，请选择 .xlsx、.xls 或 .csv 文件', 3000);
            return;
        }
        
        // 验证文件大小 (10MB)
        const maxSize = 10 * 1024 * 1024; // 10MB
        if (file.size > maxSize) {
            NotificationService.error('文件大小超过限制，最大支持 10MB', 3000);
            return;
        }
        
        // 显示文件信息
        this.showFileInfo(file);
        
        // 解析Excel文件获取工作表信息
        this.parseExcelFile(file);
    }
    
    /**
     * 显示文件信息
     */
    showFileInfo(file) {
        const dropZoneContent = document.getElementById('dropZoneContent');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        
        if (dropZoneContent && fileInfo && fileName && fileSize) {
            dropZoneContent.classList.add('hidden');
            fileInfo.classList.remove('hidden');
            fileName.textContent = file.name;
            fileSize.textContent = this.formatFileSize(file.size);
        }
    }
    
    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    /**
     * 解析Excel文件
     */
    async parseExcelFile(file) {
        try {
            NotificationService.info('正在解析Excel文件...', 2000);
            
            // 使用FileReader读取文件
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    // 使用SheetJS解析Excel文件
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    
                    // 获取工作表名称
                    const sheetNames = workbook.SheetNames;
                    this.populateSheetNames(sheetNames);
                    
                    // 显示文件预览信息
                    this.showFilePreview(workbook, sheetNames);
                    
                    NotificationService.success('文件解析成功', 2000);
                } catch (error) {
                    console.error('Excel解析失败:', error);
                    NotificationService.error('Excel文件解析失败，请检查文件格式', 3000);
                    this.removeFile();
                }
            };
            
            reader.onerror = () => {
                NotificationService.error('文件读取失败', 3000);
                this.removeFile();
            };
            
            reader.readAsArrayBuffer(file);
            
        } catch (error) {
            console.error('文件解析失败:', error);
            NotificationService.error('文件解析失败', 3000);
            this.removeFile();
        }
    }
    
    /**
     * 填充工作表名称下拉框
     */
    populateSheetNames(sheetNames) {
        const sheetSelect = document.getElementById('sheetName');
        if (!sheetSelect) return;
        
        // 清空现有选项
        sheetSelect.innerHTML = '<option value="">选择工作表</option>';
        
        // 添加工作表选项
        sheetNames.forEach(sheetName => {
            const option = document.createElement('option');
            option.value = sheetName;
            option.textContent = sheetName;
            sheetSelect.appendChild(option);
        });
        
        // 添加自定义输入选项
        const customOption = document.createElement('option');
        customOption.value = '__custom__';
        customOption.textContent = '自定义工作表名';
        sheetSelect.appendChild(customOption);
        
        // 默认选择第一个工作表
        if (sheetNames.length > 0) {
            sheetSelect.value = sheetNames[0];
        }
    }
    
    /**
     * 显示文件预览信息
     */
    showFilePreview(workbook, sheetNames) {
        const filePreview = document.getElementById('filePreview');
        const previewContent = document.getElementById('previewContent');
        
        if (!filePreview || !previewContent) return;
        
        // 获取第一个工作表的数据预览
        const firstSheetName = sheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        
        // 统计信息
        const totalRows = jsonData.length;
        const totalCols = jsonData.length > 0 ? jsonData[0].length : 0;
        
        let previewHtml = `
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <span class="text-sm text-slate-600">工作表数量:</span>
                    <p class="font-medium">${sheetNames.length}</p>
                </div>
                <div>
                    <span class="text-sm text-slate-600">数据行数:</span>
                    <p class="font-medium">${totalRows}</p>
                </div>
                <div>
                    <span class="text-sm text-slate-600">数据列数:</span>
                    <p class="font-medium">${totalCols}</p>
                </div>
                <div>
                    <span class="text-sm text-slate-600">文件大小:</span>
                    <p class="font-medium">${this.formatFileSize(workbook.Sheets[firstSheetName]['!fullref'] ? workbook.Sheets[firstSheetName]['!fullref'].length : 0)}</p>
                </div>
            </div>
        `;
        
        // 显示列名预览（前5列）
        if (totalCols > 0) {
            const headers = jsonData[0] || [];
            const headerPreview = headers.slice(0, 5).map(h => h || `列${headers.indexOf(h) + 1}`);
            previewHtml += `
                <div class="mt-3">
                    <span class="text-sm text-slate-600">列名预览:</span>
                    <div class="flex flex-wrap gap-1 mt-1">
                        ${headerPreview.map(header => `<span class="px-2 py-1 bg-slate-200 text-slate-700 rounded text-xs">${header}</span>`).join('')}
                        ${totalCols > 5 ? `<span class="px-2 py-1 bg-slate-100 text-slate-500 rounded text-xs">+${totalCols - 5} 更多</span>` : ''}
                    </div>
                </div>
            `;
        }
        
        // 显示工作表列表
        previewHtml += `
            <div class="mt-3">
                <span class="text-sm text-slate-600">工作表列表:</span>
                <div class="mt-1 space-y-1">
                    ${sheetNames.map(sheetName => `
                        <div class="flex items-center text-sm">
                            <i class="fas fa-table text-slate-400 mr-2"></i>
                            <span>${sheetName}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
        
        previewContent.innerHTML = previewHtml;
        filePreview.classList.remove('hidden');
        
        // 保存工作簿引用，供后续使用
        this.currentWorkbook = workbook;
    }
    
    /**
     * 移除文件
     */
    removeFile() {
        const dropZoneContent = document.getElementById('dropZoneContent');
        const fileInfo = document.getElementById('fileInfo');
        const filePreview = document.getElementById('filePreview');
        const fileInput = document.getElementById('excelFile');
        
        if (dropZoneContent) dropZoneContent.classList.remove('hidden');
        if (fileInfo) fileInfo.classList.add('hidden');
        if (filePreview) filePreview.classList.add('hidden');
        if (fileInput) fileInput.value = '';
        
        // 清空工作表选择
        const sheetSelect = document.getElementById('sheetName');
        if (sheetSelect) {
            sheetSelect.innerHTML = '<option value="">选择工作表</option>';
        }
        
        // 清空自定义工作表输入
        const sheetCustom = document.getElementById('sheetNameCustom');
        if (sheetCustom) {
            sheetCustom.value = '';
            sheetCustom.classList.add('hidden');
        }
        
        // 清空工作簿引用
        this.currentWorkbook = null;
    }
    
    /**
     * 测试Excel连接
     */
    async testExcelConnection() {
        const fileInput = document.getElementById('excelFile');
        if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
            NotificationService.error('请先选择Excel文件', 3000);
            return;
        }
        
        try {
            NotificationService.info('正在测试Excel文件连接...', 2000);
            
            // 创建FormData上传文件
            const formData = new FormData();
            const file = fileInput.files[0];
            const sheetName = this.getSelectedSheetName();
            const hasHeader = document.getElementById('hasHeader')?.checked || true;
            
            formData.append('file', file);
            formData.append('sheet_name', sheetName);
            formData.append('has_header', hasHeader);
            
            // 调用Excel测试连接API
            const response = await fetch('/api/data-sources/test-excel-connection', {
                method: 'POST',
                body: formData,
                headers: {
                    // 不设置Content-Type，让浏览器自动设置multipart/form-data
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                const message = `Excel文件连接成功！文件包含 ${result.data_info?.total_sheets || 0} 个工作表`;
                NotificationService.success(message, 3000);
            } else {
                NotificationService.error(result.message || '连接测试失败', 3000);
            }
            
        } catch (error) {
            console.error('Excel连接测试失败:', error);
            NotificationService.error('连接测试失败: ' + error.message, 3000);
        }
    }
    
    /**
     * 预览Excel数据
     */
    async previewExcelData() {
        const fileInput = document.getElementById('excelFile');
        if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
            NotificationService.error('请先选择Excel文件', 3000);
            return;
        }
        
        try {
            NotificationService.info('正在预览Excel数据...', 2000);
            
            // 获取当前选择的工作表
            const sheetName = this.getSelectedSheetName();
            if (!sheetName) {
                NotificationService.error('请选择工作表', 3000);
                return;
            }
            
            // 优先使用API预览，后端处理更稳定
            try {
                await this.previewExcelViaAPI(sheetName);
            } catch (apiError) {
                console.warn('API预览失败，回退到前端预览:', apiError);
                
                // API失败时，回退到前端预览
                if (this.currentWorkbook) {
                    const worksheet = this.currentWorkbook.Sheets[sheetName];
                    if (!worksheet) {
                        NotificationService.error('工作表不存在', 3000);
                        return;
                    }
                    
                    // 转换为JSON数据（前20行）
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                    const previewData = jsonData.slice(0, 20); // 前20行
                    
                    // 获取列名
                    const headers = previewData[0] || [];
                    const columns = headers.map((header, index) => ({
                        name: header || `列${index + 1}`,
                        type: 'string'
                    }));
                    
                    // 转换数据格式
                    const data = previewData.slice(1).map((row, rowIndex) => {
                        const rowData = {};
                        columns.forEach((col, colIndex) => {
                            rowData[col.name] = row[colIndex] || '';
                        });
                        return rowData;
                    });
                    
                    // 显示预览模态框
                    aiAnalysisPage.showDataPreviewModal();
                    
                    // 初始化预览表格
                    await this.initPreviewTable();
                    
                    // 加载预览数据
                    if (this.previewTable) {
                        // 提取列名数组
                        const columnNames = columns.map(col => col.name || col);
                        this.previewTable.loadData(data, columnNames, data.length, 0);
                        NotificationService.success(`前端预览数据加载成功 (工作表: ${sheetName})`, 2000);
                    }
                } else {
                    throw new Error('无法预览数据，工作簿引用丢失');
                }
            }
            
        } catch (error) {
            console.error('Excel数据预览失败:', error);
            NotificationService.error('数据预览失败: ' + error.message, 3000);
        }
    }
    
    /**
     * 通过API预览Excel数据
     */
    async previewExcelViaAPI(sheetName) {
        try {
            const fileInput = document.getElementById('excelFile');
            if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
                throw new Error('请选择Excel文件');
            }
            
            const file = fileInput.files[0];
            const hasHeader = document.getElementById('hasHeader')?.checked || true;
            
            // 创建FormData
            const formData = new FormData();
            formData.append('file', file);
            formData.append('sheet_name', sheetName);
            formData.append('has_header', hasHeader);
            formData.append('limit', 100);
            formData.append('offset', 0);
            
            // 调用预览API
            const response = await fetch('/api/data-sources/preview-excel', {
                method: 'POST',
                body: formData,
                headers: {
                    // 不设置Content-Type，让浏览器自动设置multipart/form-data
                }
            });
            
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.detail || '预览请求失败');
            }
            
            const result = await response.json();
            
            // 显示预览模态框
            aiAnalysisPage.showDataPreviewModal();
            
            // 初始化预览表格
            await this.initPreviewTable();
            
            // 加载预览数据
            if (this.previewTable) {
                // 提取列名数组
                const columnNames = result.columns.map(col => col.name || col);
                this.previewTable.loadData(
                    result.data, 
                    columnNames, 
                    result.total_records, 
                    result.execution_time
                );
                NotificationService.success(`API预览数据加载成功 (工作表: ${sheetName})`, 2000);
            }
            
        } catch (error) {
            console.error('API预览失败:', error);
            NotificationService.error('API预览失败: ' + error.message, 3000);
            throw error;
        }
    }
    
    /**
     * 获取Excel配置
     */
    getExcelConfig() {
        const fileInput = document.getElementById('excelFile');
        const sheetName = this.getSelectedSheetName();
        const hasHeader = document.getElementById('hasHeader')?.checked || true;
        
        if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
            throw new Error('请选择Excel文件');
        }
        
        return {
            type: 'excel',
            config: {
                file_path: fileInput.files[0].name, // 实际文件路径会在上传后设置
                file_name: fileInput.files[0].name,
                sheet_name: sheetName,
                has_header: hasHeader
            }
        };
    }
    
    /**
     * 获取选择的工作表名称
     */
    getSelectedSheetName() {
        const sheetSelect = document.getElementById('sheetName');
        const sheetCustom = document.getElementById('sheetNameCustom');
        
        if (sheetSelect && !sheetSelect.classList.contains('hidden')) {
            if (sheetSelect.value === '__custom__') {
                return null; // 需要使用自定义输入
            }
            return sheetSelect.value;
        }
        
        if (sheetCustom && !sheetCustom.classList.contains('hidden')) {
            return sheetCustom.value.trim() || null;
        }
        
        return null;
    }
}

// 导出为全局变量
window.DataSourceManager = DataSourceManager;